//
// Created by ldh on 22-6-8.
//

#ifndef TRACINGLOADER_TRACING_EVENT_H
#define TRACINGLOADER_TRACING_EVENT_H
#include <nlohmann/json.hpp>
#include <string>
#include <unordered_map>
#include <vector>

namespace cpp_visual {
namespace json_tool {
nlohmann::json &get_json_parser();
std::string gen_json(const std::string &json_path);
std::size_t get_json_size();
std::string get_json_str(int index);
void json_clear();


} // namespace json_tool

struct TracingConfig {
  bool enable{true};
  std::string tracing_json_path{"./result.json"};//the path to gen json
  std::int32_t max_cache{10};//write json 10 every time
};

class TracingTool {
public:
  static int64_t currentDurationTs();
  static bool loadTracingConf(const std::string& conf_path);
  static void setTracingConf(TracingConfig tracingConf);
  static const TracingConfig& getTracingConf();


  static void writeJson(const std::string& json_str);
  static void finish();


private:
  static int64_t start_time_;
  static TracingConfig conf_;
  static bool start_;
};
class TracingEvent {
public:
  template <typename FieldType>
  void setEventField(const std::string &name, const FieldType &value) {
    event_json_[name] = value;
  }
  void commitEvent();

private:
  nlohmann::json event_json_;
};

class TracingDuration : public TracingEvent {
public:
  TracingDuration(const std::string &task_name, const std::string &thread_name,
                  const std::string &duration_name);
  virtual ~TracingDuration() = default;
  void begin();
  void end();
};

#define TRACING_VISUAL_B(__TASK__, __THREAD__, __DURATION_NAME__)              \
  cpp_visual::TracingDuration __DURATION_NAME__##_BEGIN(                       \
      #__TASK__, #__THREAD__, #__DURATION_NAME__);                             \
  __DURATION_NAME__##_BEGIN.begin()

#define TRACING_VISUAL_E(__TASK__, __THREAD__, __DURATION_NAME__)              \
  cpp_visual::TracingDuration __DURATION_NAME__##_END(#__TASK__, #__THREAD__,  \
                                                      #__DURATION_NAME__);     \
  __DURATION_NAME__##_END.end()

} // namespace cpp_visual
#endif // TRACINGLOADER_TRACING_EVENT_H
